<?php

class Grillas_administrador extends CI_Model {

    function __construct() {
        parent::__construct();
    }

    private function Strip($value) {
        if (get_magic_quotes_gpc() != 0) {
            if (is_array($value))
                if ($this->array_is_associative($value)) {
                    foreach ($value as $k => $v)
                        $tmp_val[$k] = stripslashes($v);
                    $value = $tmp_val;
                }
                else
                    for ($j = 0; $j < sizeof($value); $j++)
                        $value[$j] = stripslashes($value[$j]);
            else
                $value = stripslashes($value);
        }
        return $value;
    }

    private function getStringForGroup($group) {
        $i_ = '';
        $sopt = array('eq' => "=", 'ne' => "<>", 'lt' => "<", 'le' => "<=", 'gt' => ">", 'ge' => ">=", 'bw' => " {$i_}LIKE ", 'bn' => " NOT {$i_}LIKE ", 'in' => ' IN ', 'ni' => ' NOT IN', 'ew' => " {$i_}LIKE ", 'en' => " NOT {$i_}LIKE ", 'cn' => " {$i_}LIKE ", 'nc' => " NOT {$i_}LIKE ", 'nu' => 'IS NULL', 'nn' => 'IS NOT NULL');
        $s = "(";
        if (isset($group['groups']) && is_array($group['groups']) && count($group['groups']) > 0) {
            for ($j = 0; $j < count($group['groups']); $j++) {
                if (strlen($s) > 1) {
                    $s .= " " . $group['groupOp'] . " ";
                }
                try {
                    $dat = $this->getStringForGroup($group['groups'][$j]);
                    $s .= $dat;
                } catch (Exception $e) {
                    echo $e->getMessage();
                }
            }
        }
        if (isset($group['rules']) && count($group['rules']) > 0) {
            try {
                foreach ($group['rules'] as $key => $val) {
                    if (strlen($s) > 1) {
                        $s .= " " . $group['groupOp'] . " ";
                    }
                    $field = $val['field'];
                    $op = $val['op'];
                    $v = $val['data'];
                    if ($op) {
                        switch ($op) {
                            case 'bw':
                            case 'bn':
                                $s .= $field . ' ' . $sopt[$op] . "'$v%'";
                                break;
                            case 'ew':
                            case 'en':
                                $s .= $field . ' ' . $sopt[$op] . "'%$v'";
                                break;
                            case 'cn':
                            case 'nc':
                                $s .= $field . ' ' . $sopt[$op] . "'%$v%'";
                                break;
                            case 'in':
                            case 'ni':
                                $s .= $field . ' ' . $sopt[$op] . "( '$v' )";
                                break;
                            case 'nu':
                            case 'nn':
                                $s .= $field . ' ' . $sopt[$op] . " ";
                                break;
                            default :
                                $s .= $field . ' ' . $sopt[$op] . " '$v' ";
                                break;
                        }
                    }
                }
            } catch (Exception $e) {
                echo $e->getMessage();
            }
        }
        $s .= ")";
        if ($s == "()") {
            //return array("",$prm); // ignore groups that don't have rules
            return " 1=1 ";
        } else {
            return $s;
            ;
        }
    }

//fin private function getStringForGroup($group){

    private function array_is_associative($array) {
        if (is_array($array) && !empty($array)) {
            for ($iterator = count($array) - 1; $iterator; $iterator--) {
                if (!array_key_exists($iterator, $array)) {
                    return true;
                }
            }
            return!array_key_exists(0, $array);
        }
        return false;
    }
    public function totalEmpresas() {
        //Variables del jqgrid
        $page = $this->input->post('page'); // get the requested page
        $limit = $this->input->post('rows'); // get how many rows we want to have into the grid
        $sidx = $this->input->post('sidx'); // get index row - i.e. user click to sort
        $sord = $this->input->post('sord'); // get the direction
        if (!$sidx) $sidx = 1;
        $wh = "";
        $searchOn = $this->Strip($_REQUEST['_search']);
        if ($searchOn == 'true') {
            $searchstr = $this->Strip($_REQUEST['filters']);
            $jsona = json_decode($searchstr, true);
            $wh = " AND " . $this->getStringForGroup($jsona);
        }
        $sql = "select count(emp.`empresaId`) as total from empresas emp 
                inner join usuarios usu on usu.`usuarioId` = emp.`usuarioId`
                inner join sectores sec on sec.`sectorId` = emp.`sectorId`
                inner join ciudades ciu on ciu.`ciudadId` = emp.`ciudadId`
                inner join departamentos dep on dep.`dptCod` = ciu.`dptCod` where 1= 1" . $wh;
        $query = $this->db->query($sql);
        $obj = $query->result();
        $count = $obj[0]->total;
        if ($count > 0) $total_pages = ceil($count / $limit);
        else $total_pages = 0;
        if ($page > $total_pages) $page = $total_pages;
        $start = $limit * $page - $limit; // do not put $limit*($page - 1)
        $start = ($start > 0) ? $start : 0;
        $sql = "select usu.usuario,emp.`empresaId`,emp.`empresaRazon`,emp.`empresaNit`,ciu.ciudad,sec.sector,dep.departamento,emp.`empresaDireccion`,emp.`empresaContacto`,emp.`empresaTelefono1`,emp.`empresaPagina`,emp.`empresaFechaCreo` from empresas emp 
                inner join usuarios usu on usu.`usuarioId` = emp.`usuarioId`
                inner join sectores sec on sec.`sectorId` = emp.`sectorId`
                inner join ciudades ciu on ciu.`ciudadId` = emp.`ciudadId`
                inner join departamentos dep on dep.`dptCod` = ciu.`dptCod` where 1= 1" . $wh." ORDER BY " . $sidx . " " . $sord . " LIMIT " . $start . " , " . $limit;
        $query = $this->db->query($sql);
        $responce->page = $page;
        $responce->total = $total_pages;
        $responce->records = $count;
        $i = 0;
        foreach ($query->result() as $value) {
            $responce->rows[$i]['id'] = $value->empresaId;
            $responce->rows[$i]['cell'] = array($value->empresaRazon, $value->empresaNit,$value->sector, $value->ciudad,$value->departamento,$value->empresaDireccion,$value->empresaContacto,$value->usuario,$value->empresaTelefono1,$value->empresaPagina,$value->empresaFechaCreo);
            $i++;
        }
        echo json_encode($responce);
   }
   public function totalInstituciones(){
        //Variables del jqgrid
        $page = $this->input->post('page'); // get the requested page
        $limit = $this->input->post('rows'); // get how many rows we want to have into the grid
        $sidx = $this->input->post('sidx'); // get index row - i.e. user click to sort
        $sord = $this->input->post('sord'); // get the direction
        if (!$sidx) $sidx = 1;
        $wh = "";
        $searchOn = $this->Strip($_REQUEST['_search']);
        if ($searchOn == 'true') {
            $searchstr = $this->Strip($_REQUEST['filters']);
            $jsona = json_decode($searchstr, true);
            $wh = " AND " . $this->getStringForGroup($jsona);
        }
        $sql = "select count(`institucionId`) as total from instituciones insti
                inner join usuarios usu on usu.`usuarioId` = insti.`usuarioId`
                inner join ciudades ciu on ciu.`ciudadId` = insti.`ciudadId`
                inner join departamentos dep on dep.`dptCod` = ciu.`dptCod` where 1=1 " . $wh;
        $query = $this->db->query($sql);
        $obj = $query->result();
        $count = $obj[0]->total;
        if ($count > 0) $total_pages = ceil($count / $limit);
        else $total_pages = 0;
        if ($page > $total_pages) $page = $total_pages;
        $start = $limit * $page - $limit; // do not put $limit*($page - 1)
        $start = ($start > 0) ? $start : 0;
        $sql = "select insti.*,ciu.ciudad,dep.departamento,usu.usuario from instituciones insti
                inner join usuarios usu on usu.`usuarioId` = insti.`usuarioId`
                inner join ciudades ciu on ciu.`ciudadId` = insti.`ciudadId`
                inner join departamentos dep on dep.`dptCod` = ciu.`dptCod` where 1=1 " . $wh." ORDER BY " . $sidx . " " . $sord . " LIMIT " . $start . " , " . $limit;
        $query = $this->db->query($sql);
        $responce->page = $page;
        $responce->total = $total_pages;
        $responce->records = $count;
        $i = 0;
        foreach ($query->result() as $value) {
            $responce->rows[$i]['id'] = $value->institucionId;
            $responce->rows[$i]['cell'] = array($value->institucionRazon, $value->institucionNit, $value->usuario,$value->institucionContacto,$value->institucionTelefono,$value->ciudad,$value->departamento,$value->institucionDireccion,$value->institucionPagina,$value->institucionTipoFormacion,$value->institucionEnfoquesFormacion,$value->institucionFechaCreo);
            $i++;
        }
        echo json_encode($responce);
   }
}
?>
